package com.xiaodou.mjf.web.xface.product.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.service.FinancialPackageService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.FinancingStatisticsService;
import com.xiaodou.mjf.application.core.service.InvestService;
import com.xiaodou.mjf.entity.core.FinancialPackage;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingStatistics;
import com.xiaodou.mjf.entity.core.Invest;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.Global;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.product.domain.Invester;
import com.xiaodou.mjf.web.xface.product.domain.XiaoDouProduct;

/**
 * Created by Rocky on 2/27/15.
 */
@RestController
@RequestMapping("v1/product/xiaodou")
public class XiaoDouProductController extends ApiController {

	@Resource
	FinancialPackageService financialPackageService;
	@Resource
	FinancingService financingService;
	@Resource
	FinancingStatisticsService financingStaticsService;
	@Resource
	InvestService investService;
	
	/**
	 * 小豆理财产品列表查询
	 * @return result
	 */
	@RequestMapping("")	
	public Map<String, Object> list() {
		
		Map<String,Object> result = success();

		List<XiaoDouProduct> xiaodouList = new ArrayList<XiaoDouProduct>();

		//5 boxes
		List<FinancialPackage> financialPackages = financialPackageService.list();
		
		try {
			for (FinancialPackage financialPackage : financialPackages) {
				Financing financing= financingService.getFinancingByTermAndInvsetStatus(financialPackage.getTerm(), Financing.INVEST_STATUS_SALE,Financing.TYPE_XIAODOU);
				
				Double residualAmount = 0D;
				
				if(financing != null){
					residualAmount = financingStaticsService
							.getResidualAmountByFinanceId(financing.getId());
				}
				xiaodouList.add(new XiaoDouProduct(financialPackage.getId(),
						financialPackage.getName(), financialPackage.getTerm(),
						financialPackage.getInterestRate(), financialPackage
						.getMinAmount(),financialPackage.getStatus(), residualAmount));
			}

			result.put("items", xiaodouList);
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.XIAODOU_RECORD_NOT_EXIST);
		}

		return result;
	}

	/**
	 * 小豆理财产品详情查询
	 * @param id
	 * @return result
	 */
	@RequestMapping("{id}")
	public Map<String, Object> get(@PathVariable String id) {


		// 从financial_package表查询基本信息
		FinancialPackage financialPackage = financialPackageService.get(id);
		Integer investCount = 0;
		if (financialPackage == null) {
			return failure(ResultCode.XIAODOU_DETAIL_RECORD_NOT_EXIST);
		}
		try {
			
			Map<String,Object> result = success();
			// 从financing表查询status=0（正常），并且invest_status!=4（不流标），并且按照周期来计算amount的sum值
			Financing financing= financingService.getFinancingByTermAndInvsetStatus(financialPackage.getTerm(), Financing.INVEST_STATUS_SALE,Financing.TYPE_XIAODOU);
			
			Double residualAmount = 0D;
			Double totalAmount = financingService.getTotalAmountByTerm(financialPackage.getTerm());
			
			if(financing != null){
				FinancingStatistics fs = financingStaticsService.findByfinanceId(financing.getId());				
				residualAmount = fs == null ? 0D : fs.getResidualAmount();				
			}
			investCount = investService.countPerson(financialPackage.getTerm(), Financing.TYPE_XIAODOU);
			result.put("id", financialPackage.getId());
			result.put("name", financialPackage.getName());
			result.put("interest_rate", financialPackage.getInterestRate());
			result.put("term", financialPackage.getTerm());
			result.put("invest_count", investCount);
			result.put("total_amount",totalAmount);
			result.put("residual_amount", residualAmount);
			result.put("value_date", financialPackage.getValueDate());
			result.put("settlement_date", financialPackage.getSettlementDate());
			result.put("min_amount", financialPackage.getMinAmount());
			result.put("agreement_title", financialPackage.getAgreementTitle());
			result.put("agreement_url", financialPackage.getAgreementUrl());

            return result;
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.XIAODOU_DETAIL_RECORD_NOT_EXIST);
		}
		
	}

	/**
	 * 小豆理财产品项目介绍详情查询
	 * @param id
	 * @return result
	 */
	@RequestMapping("{id}/borrower")
	public Map<String, Object> borrower(@PathVariable String id) {

		// 从financial_package表查询基本信息
		FinancialPackage financialPackage = financialPackageService.get(id);
		if (financialPackage == null) {
			return failure(ResultCode.XIAODOU_PROJECT_RECORD_NOT_EXIST);
		}

		Map<String,Object> result = success();
		result.put("borrower", financialPackage.getBorrower());
		result.put("purpose", financialPackage.getPurpose());
		result.put("description", financialPackage.getDescription());

		return result;
	}

	/**
	 * 小豆理财风险控制信息查询
	 * @param id
	 * @return result
	 */
	@RequestMapping("{id}/risk_control")
	public Map<String, Object> risk(@PathVariable String id) {

		// 从financial_package表查询基本信息
		FinancialPackage financialPackage = financialPackageService.get(id);
		if (financialPackage == null) {
			return failure(ResultCode.XIAODOU_RISK_RECORD_NOT_EXIST);
		}

		String imageServer = Global.getImgPath();

		Map<String,Object> result = success();
		result.put("risk_control_description",
				financialPackage.getRiskControlDescription());
		//String[] images = financialPackage.getRiskControlImages().split(",");
		String[] imagesAfter = new String[1];
//		for (int i = 0; i < images.length; i++) {
//			imagesAfter[i] = imageServer + images[i];
//		}
        imagesAfter[0] = imageServer + financialPackage.getImage1();
//        imagesAfter[1] = imageServer + financialPackage.getImage2();
		result.put("items", imagesAfter);

		return result;
	}

	/**
	 * 小豆理财投标记录查询
	 * @param id
	 * @param start
	 * @param row
	 * @return result
	 */
	@RequestMapping("{id}/investers")
	public Map<String, Object> investers(@PathVariable String id,
			Integer start, Integer row) {

		if (start == null || start < 0) {
			start = 0;

		}

		if (row == null) {
			row = 20;
		}

		// 从financial_package表查询基本信息,获取term
		FinancialPackage financialPackage = financialPackageService.get(id);
		if (financialPackage == null) {
			return failure(ResultCode.XIAODOU_INVEST_RECORD_NOT_EXIST);
		}

		// 通过从financial_package表中得到的term查询invest的所有记录
		Invest invest = new Invest();
		invest.setStart(start);
		invest.setLimit(row);
		invest.setTerm(financialPackage.getTerm());
		invest.setType(Financing.TYPE_XIAODOU);
		//只查出已购买的投标记录
		invest.setPaymentStatus(Invest.INVEST_PAYMENT);

		Page<Invest> page = investService.pageForPerson(invest);
		if (page == null) {
			return failure(ResultCode.XIAODOU_INVEST_RECORD_NOT_EXIST);
		}
		List<Invest> investList = page.getContent();

		List<Invester> invester = new ArrayList<Invester>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		for (Invest invests : investList) {
			invester.add(new Invester(invests.getMemberName()==null?"":invests.getMemberName(), invests
					.getAmount(), sdf.format(invests.getInvestDate()).toString()));
		}

		Map<String,Object> result = success();
		result.put("items", invester);

		return result;
	}

}
